package com.wan.personnel2.web.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wan.personnel2.common.Const;
import com.wan.personnel2.entity.DocumentInf;
import com.wan.personnel2.entity.UserInf;
import com.wan.personnel2.service.DocumentInfService;
import com.wan.personnel2.util.FileUtil;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

import java.util.Date;
import java.util.List;

@RequestMapping("/documentInf")
@Controller
public class DocumentInfController {
    @Autowired
    private DocumentInfService service;

    @RequestMapping("/list")
    public  String getDocList(Model model){
        List<DocumentInf> list = service.list();

        model.addAttribute("list1",list);

       System.out.println(" =============================");
        System.out.println(" =============================");
        System.out.println(" =============================");
        System.out.println(" =============================");
        System.out.println(list);
        System.out.println(" =============================");
        System.out.println(" =============================");
        System.out.println(" =============================");
        System.out.println(" =============================");
//        获取所有上传用户信息
        return "document/list";
    }

    @RequestMapping("/add")
    public String fileupload(String remark, String title, MultipartFile file, HttpSession session) throws IOException {
        UserInf userInf = (UserInf) session.getAttribute(Const.IS_LOGIN);
        if (userInf == null) {
            return "redirect:/documentInf/list";
        }
//        获取文件的名称
        String filename = file.getOriginalFilename();
//        保存服务器的文件名
        String newFileName = FileUtil.renameFile(filename);
//        获取项目部署路径
        String realPath = session.getServletContext().getRealPath("/upload");
//        处理文件目录是否存在
        File f = new File(realPath);
        if (!f.exists()) {
//            不存在就创建
            f.mkdir();
        }

//        把文件保存再服务器中
        file.transferTo(new File(realPath+"\\"+newFileName));
//        访问业务层新增上传文件保存数据库里
        //创建documentInf对象设置数据

        DocumentInf doc = new DocumentInf(title,filename,remark,new Date(), userInf.getId());
        boolean ans = service.addFile(doc);


        return "welcome";
    }

}
